<?php
namespace app\school\controller;

use cmf\controller\AdminBaseController;
use think\Db;
use app\school\model\SchoolTeacherModel;

class AdminTeacherController extends AdminBaseController
{
    public function index()
    {
        $model = new SchoolTeacherModel();
        $data = $model->teacherList();
        $this->assign('list',$data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }

    public function addPost()
    {
        $schoolTeacherModel = new SchoolTeacherModel();

        $data = $this->request->param();

        $result = $this->validate($data, 'SchoolTeacher');

        if ($result !== true) {
            $this->error($result);
        }

        $result = $schoolTeacherModel->allowField(true)->save($data);

        if ($result === false) {
            $this->error('添加失败!');
        }

        $this->success('添加成功!', url('AdminTeacher/index'));

    }

    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id > 0) {
            $teacher = SchoolTeacherModel::get($id)->toArray();            
            $this->assign($teacher);            
            return $this->fetch();
        } else {
            $this->error('操作错误!');
        }
    }

    public function editPost()
    {
        $data = $this->request->param();
        $id          = intval($data['id']);
        $result = $this->validate($data, 'SchoolTeacher');

        if ($result !== true) {
            $this->error($result);
        }

        $schoolTeacherModel = new SchoolTeacherModel();

        $result = $schoolTeacherModel->isUpdate(true)->allowField(true)->save($data, ['id' => $id]);

        if ($result === false) {
            $this->error('保存失败!');
        }

        $this->success('保存成功!');
    }

    public function delete()
    {
        $SchoolTeacherModel = new SchoolTeacherModel();
        $id                  = $this->request->param('id');
        //获取删除的内容
        $findTeacher = $SchoolTeacherModel->where('id', $id)->find();

        if (empty($findTeacher)) {
            $this->error('科目不存在!');
        }
//判断此分类有无子分类（不算被删除的子分类）
        
        $data   = [
            'object_id'   => $findTeacher['id'],
            'create_time' => time(),
            'table_name'  => 'school_Teacher',
            'name'        => $findTeacher['name']
        ];
        $result = $SchoolTeacherModel
            ->where('id', $id)
            ->update(['delete_time' => time()]);
        if ($result) {
            Db::name('recycleBin')->insert($data);
            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }

    public function listOrder()
    {        
        parent::listOrders(Db::name('school_teacher'));
        $this->success("排序更新成功！", '');
    }
}

